#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : 河北雪域网络科技有限公司 A.Star
# @contact: astar@snowland.ltd
# @site: 
# @file: pso_demo.py
# @time: 2018/8/1 9:04
# @Software: PyCharm


from slapy.swarm.pso import PSOEngine
import numpy as np
# 使用前请安装文件
# pip install snowland-algorithm
# 确保版本号大于0.0.2

# 求 z = cos(x) + sin(x) - x * y (x in [0, 2*pi], y in [0, 2*pi]) 的最大值

def fun(vars):
    # 评价函数
    x, y = vars
    x = x * 2 * np.pi  # 反归一化
    y = y * 2 * np.pi
    if 0 <= x <= 2 * np.pi and 0 <= y <= np.pi:
        return np.cos(x) + np.sin(x) - x * y
    else:
        return -2 - 4 * np.pi ** 2 # 返回一个达不到的小值


if __name__ == '__main__':
    engine = PSOEngine(vmax=0.01, min_fitness_value=-1, dim=2, fitness_function=fun, steps=100)
    engine.run()
    x, y = engine.gbest.chromosome
    print('计算得到的最大值是', fun(engine.gbest.chromosome))
    print('x取值是:', x * 2 * np.pi, 'y取值是:', y * 2 * np.pi)  # 需要反归一化
